<template>
  <div class="carTree">
    <div class="header">
      <ul @click="treeTypeChange">
        <li :class="{choosed: treeType == '全部'}">
          全部
          <div class="line"></div>
        </li>
        <li :class="{choosed: treeType == '收藏'}">
          收藏
          <div class="line"></div>
        </li>
        <li :class="{choosed: treeType == '分组'}">分组</li>
      </ul>
    </div>
    <div class="search">
      <el-input placeholder="请输入车牌号码" size="small" v-model="searchCar"  @keyup.enter.native="searchCarFunc()">
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-button type="info" size="small" icon="el-icon-refresh" style="border-left:none;" @click="updateTruckList()"></el-button>
      <el-button type="info" size="small" icon="el-icon-s-tools" style="border-left:none; border-radius: 0 4px 4px 0;"></el-button>
    </div>
    <div class="content">
      <el-tree
        ref="tree"
        node-key="id"
        :data="data" 
        :props="defaultProps"
        @check="checkChange"
        @node-click="onNodeClick"
        :filter-node-method="filterNode"
        :show-checkbox="isCheck">
         <!-- @dblclick="clickNode(node, data)" -->
        <div slot-scope="{ node, data }" class="cus-node">
          <img v-if="data.children" src="../../../../public/img/bg/文件夹.png" alt="">
          <template v-else>
            <img v-if="data.location.status == '1' && data.location.speed" src="../../../../public/img/bg/车辆.png" alt="">
            <img v-if="data.location.status == '1' && !data.location.speed" src="../../../../public/img/bg/停止.png" alt="">
            <img v-if="data.location.status == '2'" src="../../../../public/img/bg/离线车辆.png" alt="">
            <img v-if="data.location.status == '3'" src="../../../../public/img/bg/未激活车辆.png" alt="">
          </template>
          
          <span>{{ node.label }}</span>
          <span v-if="data.location && data.location.status && isShowStatus">【{{ (isShowLastUpldateTime ? data.location.locateTimeStr : '') + getStatus(data.location.status) }}-{{ data.location.speed > 0 ? '行驶' : '停止' }}】</span>
          <img v-if="!data.children && isShowHistoryIcon " style="margin-left: 5px;" src="../../../../public/img/bg/播放.png" alt="" @click="historyPlay(data.deviceNo, data.name)">
          
        </div>
      </el-tree>
    </div>
  </div>
</template>
<script>
import { getTruckList } from '@/api/jgsb/graphic/truckLocation'
export default {
  props: {
    isCheck: {
      type: Boolean,
      default: true
    },
    isShowHistoryIcon: {
      type: Boolean,
      default: true
    },
    isShowLastUpldateTime: {
      type: Boolean,
      default: true
    },
    isShowStatus: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      treeType: '全部',
      searchCar: '',
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      timer: null,      //定时器
      carList: null,      //初始化车辆列表（对象形式）
      updateCarList: [],//定时器车辆列表

      checkedNodes: [],
      currentChoosedNode: null,
    }
  },
  methods: {
    searchCarFunc() {
      this.$refs.tree.filter(this.searchCar);
    },

    filterNode(value, data) {
       if (!value) return true;
        return data.name.indexOf(value) !== -1;
        //  || data.deviceNo.indexOf(value) !== -1
    },

    //历史轨迹回放
    historyPlay(deviceNo, vehicleNumber) {
      this.$emit('historyPlay', deviceNo, vehicleNumber)
    },

    //根据状态码获取车辆设备状态
    getStatus(status) {
      if(status == 1)
        return '在线'
      if(status == 2)
        return '离线'
      if(status == 3)
        return '未激活'
    },
    //类型点击事件
    treeTypeChange(e) {
      this.treeType = e.target.innerText || '全部'
    },

    //树双击事件
    clickNode(node, data) {
      //this.$emit('monitorCarChange', 'add', data)
      this.$refs.tree.setChecked(data.id, true, false)
    },

    //节点单
    onNodeClick(obj, nodeData, tree) {
      this.$emit('nodeClick', obj)
    },

    //节点改变事件
    checkChange(data, node) {
      this.checkedNodes = node.checkedNodes
      this.currentChoosedNode = data
      
      this.$emit('monitorCarChange', node.checkedNodes, data)
    },

    //递归获取车辆信息
    getCarList(arr, key) {
      arr.forEach(item => {
        if(!!item.children) {
          this.getCarList(item.children, key)
        }
        else {
          if(key == 'carList')
            this[key][item.id] = item 
          else
            this[key].push(item)
        }
      });
    },

    //获取车辆树
    getTruckList() {
      this.carList = {}
      getTruckList().then(res => {
        if(res.data.success) {
          this.data = [res.data.data]
          this.getCarList([res.data.data], 'carList')
        }
      })
    },

    //更新车辆信息
    updateTruckList() {
      this.updateCarList = []
      getTruckList().then(res => {
        if(res.data.success) {
          this.getCarList([res.data.data], 'updateCarList')

          this.updateCarList.forEach((item) => {
            // if(index == 0) {
            //   item.location.status = '3'
              
            // }
            const obj = this.carList[item.id]
            if(obj) {
              obj.location.status = item.location.status
              obj.location.address = item.location.address
              obj.location.carNumber = item.location.carNumber
              obj.location.chargerState = item.location.chargerState
              obj.location.device = item.location.device
              obj.location.lat = item.location.lat
              obj.location.lng = item.location.lng
              obj.location.locateTimeStr = item.location.locateTimeStr
              obj.location.locateType = item.location.locateType
              obj.location.powerRate = item.location.powerRate
              obj.location.status = item.location.status
              obj.location.speed = item.location.speed
            }
          })
          this.$emit('monitorCarChange', this.checkedNodes, {}, 'update')
        }
      })

    },

    //区域外点击事件
    handleDocumentClick(e) {
      if (!this.$el.contains(e.target)) 
      {
        let el = this.$parent.$children.filter(item=>item.$el.className==='chsEqp')
        if(el.length==0)
            return
        if(el[0].$el.contains(e.target))
            return
        this.$emit('on-outside-click')
      } 
    },
  },
  mounted() {
    this.getTruckList()
  },
  activated() {  
    this.timer = window.setInterval(this.updateTruckList, 15000)
    document.addEventListener('click',this.handleDocumentClick)
  },
  deactivated() {
    window.clearInterval(this.timer)
    document.removeEventListener('click',this.handleDocumentClick)
  },
  beforeDestroy() {
    window.clearInterval(this.timer)
    document.removeEventListener('click',this.handleDocumentClick)
  }
}
</script>
<style lang="scss" scoped>
.carTree {
  width: 100%;
  height: 100%;
  
  background-color: #fff;
  display: flex;
  flex-direction: column;
  .header {
    height: 40px;
    width: 100%;
    ul,li{list-style:none;} 
    ul {
      display: flex; padding: 0; margin: 0;
      height: 100%;
      li {
        width: 33.33%;
        font-size: 12px;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        cursor: pointer;
        .line { 
          position: absolute; 
          right: 0;
          top: 11px;
          height: 18px;
          border-right: 1px solid #eee;
        }
        // &:not(:first-child){
        //   border-left: 1px solid #eee;
        // }
      }
      .choosed {
        border-bottom: 2px solid #6496cb;
        font-weight: 600;
        color: #6496cb !important;
      }
    }
  }
  .search {
    height: 46px;
    width: 100%;
    background-color: #eee;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 5px;
    box-sizing: border-box;
    .el-button { margin: 0; padding: 3px 15px; border-radius: 0; height: 36px; border-color: #D6D6D6; }
    ::v-deep .el-input__inner { height: 36px !important; line-height: 36px; border-radius: 4px 0 0 4px;}
  }
  .content {
    flex: 1;
    overflow: auto;
    font-size: 14px;
    overflow-x: scroll;
    display: grid;
    .cus-node {
      display: flex;
      align-items: center;
      img { width: 18px; height: 18px; margin-right:3px; }
    }
  }
}
</style>